<%@ page import="java.util.NavigableSet" %>
<%
    /*获取项目的根路径*/
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    /*basePath就是得到的跟路径类似于：http://localhost:8081/test/*/
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LoveU-遇见更好的你</title>
    <link rel="shortcut icon" href="<%=basePath%>/img/男女混合.png" type="image/x-icon">
    <link rel="stylesheet" href="<%=basePath%>/css/individual.css">
    <link rel="stylesheet" href="<%=basePath%>/css/iconfont/iconfont.css">
    <script src="<%=basePath%>/js/jquery-3.6.3.min.js"></script>
    <script src="<%=basePath%>/js/jquery.validate.min.js"></script>
    <style>
        .error {
            color: red;
            z-index: 10;
        }
    </style>
</head>

<body>

<%@include file="top.jsp" %>

<div class="content">
    <form action="UserServlet?method=editUser" method="post" id="registerForm" enctype="multipart/form-data">

        <input type="hidden" id="id" name="id" value="${resultVO.data.id}">

        <div class="input-item">

            <c:if test="${empty resultVO.data.avatar}">
                <img id="userAvatar" src="<%=basePath%>/img/水豚.webp" style="width: 100px;">
            </c:if>
            <c:if test="${resultVO.data.avatar != null}">
                <img id="userAvatar" src="${resultVO.data.avatar}" style="width: 100px;">
                <a href="UserServlet?method=download&fileUrl=${resultVO.data.avatar}">下载图片</a>
            </c:if>
            <input type="file" id="avatar" name="avatar" onchange="changeImage(this)"><br>
            <input type="hidden" id="user-avatar" name="user-avatar" value="${resultVO.data.avatar}">
        </div>

        <div class="input-item">
            <input type="text" id="name" name="name" placeholder="账号" value="${resultVO.data.name}">
        </div>
        <div class="input-item">
            <input type="password" id="password" name="password" value="${resultVO.data.password}">
        </div>
        <div class="input-item">
            <c:if test="${resultVO.data.gender eq '男'}">
                <label for="male">性别</label>
                <input type="radio" id="male" name="gender" value="男" checked>
                男
                <input type="radio" id="female" name="gender" value="女">
                女
                <br>
            </c:if>
            <c:if test="${resultVO.data.gender eq '女'}">
                <label for="male">性别</label>
                <input type="radio" id="male" name="gender" value="男">
                男
                <input type="radio" id="female" name="gender" value="女" checked>
                女
            </c:if>
            <c:if test="${empty resultVO.data.gender}">
                <label for="male">性别</label>
                <input type="radio" id="male" name="gender" value="男" checked>
                男
                <input type="radio" id="female" name="gender" value="女">
                女
            </c:if>
        </div>

        <div class="input-item">
            <input type="date" name="birthday" id="birthday" value="${resultVO.data.birthday}">
        </div>

        <div class="input-item">
            <select name="education" id="education">
                <option value="小学" ${resultVO.data.education == '小学' ? 'selected' : ''}>小学</option>
                <option value="初中" ${resultVO.data.education == '初中' ? 'selected' : ''}>初中</option>
                <option value="高中" ${resultVO.data.education == '高中' ? 'selected' : ''}>高中</option>
                <option value="大专" ${resultVO.data.education == '大专' ? 'selected' : ''}>大专</option>
                <option value="本科" ${resultVO.data.education == '本科' ? 'selected' : ''}>本科</option>
                <option value="硕士" ${resultVO.data.education == '硕士' ? 'selected' : ''}>硕士</option>
                <option value="博士" ${resultVO.data.education == '博士' ? 'selected' : ''}>博士</option>
                <option value="留学/海归" ${resultVO.data.education == '留学/海归' ? 'selected' : ''}>留学/海归</option>
            </select>
        </div>

        <div class="input-item">
            <label style="color: #666666;font-size: 14px">
                人物性格（填写方法如下(用'-'分割)）:
                文艺青年-摄影师-翻山越岭只为吃-二次元
                -轻音乐-小萝莉-小鲜肉-八块腹肌-御姐-旅游达人
                -舔狗-海王-空军钓鱼手-程序猿(仅供参考)
            </label>
            <br>
            <input type="text" id="likeType" name="likeType" placeholder="阳光-开朗-活泼" value="${resultVO.data.likeType}">
        </div>
        <div class="input-item">
            <label for="hobby">爱好:</label>
            <br>
            <textarea name="hobby" id="hobby">${resultVO.data.hobby}</textarea><br>
        </div>
        <div class="input-item">
            <label for="address">地址:</label>
            <br>
            <textarea name="address" id="address">${resultVO.data.address}</textarea>
        </div>
        <div class="input-item">
            <label for="motto">个性签名:</label>
            <br>
            <textarea name="motto" id="motto">${resultVO.data.motto}</textarea>
        </div>
        <div class="bottom-item">
            <button type="submit">添加</button>
            <button type="reset">重置</button>
        </div>

        <div class="publish-zone">
            <a href="publish.jsp" target="_blank">去发动态</a>
        </div>
    </form>


    <div class="zone-list">
        <c:if test="${empty myZones}">
            <div style="font-size: 25px;color: #666666; margin-left: 200px;margin-top: 200px;">您还未发布过动态，快去发布吧!</div>
        </c:if>

        <c:if test="${not empty myZones}">
            <c:forEach items="${myZones}" var="zone">
                <div class="comment-item">
                    <div class="comment-item-top">
                        <div class="item-top-left">
                            <a href="">
                                <img src="${resultVO.data.avatar}" alt="" class="user-avatar">
                            </a>
                            <div class="item-info">
                                <span class="username">${resultVO.data.name}</span>
                                <span>
                            <span class="publish-time">
                                    ${zone.publishtime}
                            </span>
                            <span class="signature">${resultVO.data.motto}</span>
                        </span>

                            </div>
                        </div>
                        <div class="item-top-right">
<%--                            <a href="" class="follow">+关注</a>--%>
                        </div>
                    </div>
                    <div class="comment-body">
                            ${zone.contenttext}
                        <div class="illustration">
                            <c:if test="${not empty zone.imgs}">
                                <c:set var="imageUrls" value="${zone.imgs}"/>
                                <c:set var="imageUrlArray" value="${fn:split(imageUrls, '+')}"/>
                                <c:forEach var="imageUrl" items="${imageUrlArray}">
                                    <img src="${imageUrl}" alt="Image"/>
                                </c:forEach>
                            </c:if>
                        </div>
                        <div class="comment-item-bottom" data-id="${zone.zoneid}">
                            <div class="icon  collect  is-collected">
                                <i class="iconfont icon-aixin heart"></i>
                                <span class="goodcount">${zone.goodcount}</span>
                            </div>
                            <div class="icon">
                                <i class="iconfont icon-chat"></i>
                                <span class="commentcount">${zone.commentcount}</span>
                            </div>
                            <div class="icon">
                                <i class="iconfont icon-zhuanfa"></i>
                                <span class="transmitcount">${zone.transmitcount}</span>
                            </div>
                        </div>

                        <div class="comment-area" style="display: none" data-id="${zone.zoneid}">
                            <div class="publish-comment">
<%--                                <img src="${zone.avatar}" alt="" class="publish-avatar">--%>
                                <c:choose>
                                    <c:when test="${not empty user.avatar}">
                                        <img src="${user.avatar}" alt="" class="publish-avatar" width="45px" height="45px">
                                    </c:when>
                                    <c:otherwise>
                                        <img src="<%=basePath%>/img/水豚.webp" alt="" class="publish-avatar" width="45px">
                                    </c:otherwise>
                                </c:choose>
                                <textarea placeholder="发布评论你的评论" class="comment-content"></textarea>
                                <a href="javascript:;" style="display: block;" class="remark" data-id="${zone.zoneid}">评论</a>
                            </div>
                            <div class="comments-list">
                            </div>
                        </div>

                    </div>
                </div>
            </c:forEach>
        </c:if>


    </div>

</div>

<%@include file="myFooter.jsp" %>

<script>

    $(function () {

        //查询对应动态的评论
        $(".comment-area").each(function () {
            let commentarea = $(this);
            let zoneid = commentarea.attr("data-id");
            $.ajax({
                url: "CommentServlet?method=getCommentByZoneId",
                type: "post",
                data: {"zoneid": zoneid},
                success: function (data) {
                    // console.log(data.data);
                    if (data == null) {
                        commentarea.find(".comments-list").html("<span>暂无评论,快来评论一下吧！</span>")
                    } else {
                        let $commentList = commentarea.find(".comments-list");
                        $commentList.empty();
                        for (let i = 0; i < data.length; i++) {
                            var comment_item = `
                        <div class="comment">
                            <div class="comment-top">
                                <img src="` + data[i].avatar + `" alt="">
                                <span>
                                    <span class="remarker-name">` + data[i].username + `</span>
                                    <br>
                                    <span class="comment-time">` + data[i].commenttime + `</span>
                                </span>
                            </div>
                            <div class="contenttext">
                                ` + data[i].contenttext + `
                            </div>
                        </div>
                            `;
                            $commentList.append(comment_item);
                        }
                    }
                }
            })
        })

        //计算评论数
        $(".commentcount").each(function (){
            let $this=$(this);
            let zoneid=$this.parent().parent().attr("data-id");
            $.ajax({
                url:"CommentServlet?method=countComment",
                type:"post",
                data:{"zoneid":zoneid},
                success:function (data){
                    $this.text(data);
                }
            })
        })
    })
    //生成评论
    $(".remark").click(function () {
        let text = $(this).prev(".comment-content").val();
        let commentarea = $(this).parent().parent(".comment-area");
        let id = $(this).attr("data-id");
        let $this=$(this)
        $.ajax({
            url: "CommentServlet?method=addComment",
            type: "post",
            data: {"id": id, "commenttext": text},
            success: function (data) {
                let count=$this.parent().parent().prev(".comment-item-bottom").find(".commentcount").text();
                count = parseInt(count, 10) || 0;
                count++;
                $this.parent().parent().prev(".comment-item-bottom").find(".commentcount").text(count);
                if (data.code == 0) {
                    //返回刷新评论区
                    $.ajax({
                        url: "CommentServlet?method=getCommentByZoneId",
                        type: "post",
                        data: {"zoneid": id},
                        success: function (data) {

                            if (data == null) {
                                commentarea.find(".comments-list").html("<span>暂无评论,快来评论一下吧！</span>")
                            } else {
                                //将文本框内容置为空
                                text = '';

                                let $commentList = commentarea.find(".comments-list");
                                $commentList.empty();
                                for (let i = 0; i < data.length; i++) {
                                    var comment_item = `
                        <div class="comment">
                            <div class="comment-top">
                                <img src="` + data[i].avatar + `" alt="">
                                <span>
                                    <span class="remarker-name">` + data[i].username + `</span>
                                    <br>
                                    <span class="comment-time">` + data[i].commenttime + `</span>
                                </span>
                            </div>
                            <div class="contenttext">
                                ` + data[i].contenttext + `
                            </div>
                        </div>
                            `;
                                    $commentList.append(comment_item);
                                }
                            }
                        }
                    })
                } else {
                    alert("fail");
                }
            }
        })
        $(this).prev(".comment-content").val("");
    })

    //点击评论图标展开评论区
    $('.icon-chat').on('click', function () {
        $(this).toggleClass('color-icon');
        var commentArea = $(this).closest('.comment-body').find('.comment-area');
        commentArea.toggle(); // 使用toggle()方法来切换显示状态
    });

    $(function () {
        //动态时间
        function updateTimeDisplay() {
            $('.publish-time').each(function () {
                var timeString = $(this).text(); // 获取时间字符串
                var date = new Date(timeString); // 尝试将时间字符串转换为Date对象

                if (!isNaN(date.getTime())) { // 检查Date对象是否有效
                    var timestamp = date.getTime(); // 获取时间戳（毫秒）
                    var now = new Date().getTime(); // 当前时间的时间戳（毫秒）
                    var diff = now - timestamp; // 时间差（毫秒）

                    if (diff < 60000) { // 如果在一分钟内
                        $(this).text('刚刚');
                    } else if (diff < 3600000) { // 如果在一个小时内
                        var minutes = Math.floor(diff / 60000);
                        $(this).text(minutes + '分钟前');
                    } else if (diff < 86400000) { // 如果在一天内
                        var hours = Math.floor(diff / 3600000);
                        $(this).text(hours + '小时前');
                    } else if (diff < 604800000) { // 如果在一个星期内
                        var days = Math.floor(diff / 86400000);
                        $(this).text(days + '天前');
                    } else {
                        // 如果超过一个星期，则显示原始时间字符串（或进行其他处理）
                        $(this).text(timeString);
                    }
                } else {
                    console.error('Invalid date string:', timeString);
                    $(this).text('无效时间');
                }
            });
        }

        // 首次加载时更新显示
        updateTimeDisplay();
        // 每隔一定时间（比如每分钟）更新一次
        //setInterval(updateTimeDisplay, 60000);

        $('form').on('submit', function (event) {
            //event.preventDefault(); // 阻止表单的默认提交行为

            // 使用jQuery的.map()方法来收集所有选中的likeType复选框的值
            var selectedValues = $('input[name="likeType"]:checked').map(function () {
                return this.value;
            }).get(); // .get()将jQuery对象转换为数组

            // 在控制台中打印所有选中的值
            console.log(selectedValues);
        });

        // 在键盘按下并释放及提交后验证提交表单
        $("#registerForm").validate({
            rules: {
                name: {required: true, rangelength: [2, 10]},
                password: {required: true, rangelength: [6, 15]},
                gender: {required: true},
                birthday: {required: true},
                education: {required: true},
                address: {required: true},
                motto: {required: true}
            },
            messages: {
                name: {required: "请输入用户名!", rangelength: "用户名长度在5到10之间!"},
                password: {required: "请输入密码！", rangelength: "密码长度在6到15之间"},
                gender: {required: "请选择您的性别!"},
                birthday: {required: "请输入您的生日!"},
                education: {required: "请选择学历！"},
                address: {required: "请输入住址!"},
                motto: {required: "请输入个性签名！"}
            }
        });

    })


    function changeImage(file) {
        $("#userAvatar").attr("src", URL.createObjectURL(file.files[0]));
    }

    function updateCommentTimeDisplay() {
        $('.comment-time').each(function () {
            var timeString = $(this).text(); // 获取时间字符串
            var date = new Date(timeString); // 尝试将时间字符串转换为Date对象

            if (!isNaN(date.getTime())) { // 检查Date对象是否有效
                var timestamp = date.getTime(); // 获取时间戳（毫秒）
                var now = new Date().getTime(); // 当前时间的时间戳（毫秒）
                var diff = now - timestamp; // 时间差（毫秒）

                if (diff < 60000) { // 如果在一分钟内
                    $(this).text('刚刚');
                } else if (diff < 3600000) { // 如果在一个小时内
                    var minutes = Math.floor(diff / 60000);
                    $(this).text(minutes + '分钟前');
                } else if (diff < 86400000) { // 如果在一天内
                    var hours = Math.floor(diff / 3600000);
                    $(this).text(hours + '小时前');
                } else if (diff < 604800000) { // 如果在一个星期内
                    var days = Math.floor(diff / 86400000);
                    $(this).text(days + '天前');
                } else {
                    // 如果超过一个星期，则显示原始时间字符串（或进行其他处理）
                    $(this).text(timeString);
                }
            } else {
                $(this).text('无效时间');
            }
        });
    }

    // 首次加载时更新显示
    updateCommentTimeDisplay();


    //点击转发转发该动态
    $(".icon-zhuanfa").click(function (){
        let $this=$(this);
        let zoneid=$this.parent().parent().attr("data-id");
        console.log("transmit->",zoneid);
        $.ajax({
            url:"ZoneServlet?method=countTransmit",
            type:"post",
            data:{"zoneid":zoneid},
            success:function (data){
                $this.next(".transmitcount").text(data);
            }
        })
    })

    //检查是否收藏该动态
    $(".collect").each(function (){
        let $this=$(this);
        let zoneid=$this.closest('[data-id]').attr("data-id");
        $.ajax({
            url:"ZoneServlet?method=checkCollected",
            type:"post",
            data:{"zoneid":zoneid},
            success:function (data){
                if (data!==1){
                    $this.removeClass("is-collected");
                }else{
                    $this.addClass("is-collected");
                    $this.find(".heart").removeClass("icon-aixin");
                }
            }
        })
    })

    //点击爱心图标收藏该动态
    $(".collect").click(function() {
        let $this = $(this);
        let zoneid = $this.closest('[data-id]').attr("data-id"); // 使用 closest 简化父级选择器
        //判断是否有is-collected
        if ($this.hasClass("is-collected")){
            //包含is-collected，进行取消收藏操作
            console.log("cancel");
            $.ajax({
                url:"ZoneServlet?method=cancelZone",
                type:"post",
                data:{"zoneid":zoneid},
                success:function (data){
                    if (data!==0){
                        $this.removeClass("is-collected");
                        $this.find(".heart").addClass("icon-aixin");
                        let goodcount=$this.find(".goodcount").text();
                        goodcount=parseInt(goodcount);
                        goodcount--;
                        if (goodcount===0){
                            $this.find(".goodcount").text("");
                        }else {
                            $this.find(".goodcount").text(goodcount);
                        }
                        alert("已取消收藏!");
                    }
                }
            })
        }else {
            //此时是不包含"is-collected"的，则添加"is-collected"
            console.log("collect")
            $.ajax({
                url:"ZoneServlet?method=collectZone",
                type:"post",
                data:{"zoneid":zoneid},
                success:function (data){
                    if (data!==0){
                        $this.addClass("is-collected");
                        $this.find(".heart").removeClass("icon-aixin");
                        let goodcount=parseInt(data);
                        goodcount++;
                        if (goodcount===0){
                            $this.find(".goodcount").text(null);
                        }else {
                            $this.find(".goodcount").text(goodcount);
                        }
                        alert("收藏成功!")
                    }
                }
            })
        }
    });


</script>
</body>

</html>